package com.huaxin.hxcloud.find.view;

import android.animation.LayoutTransition;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.AppBarLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.emmp_ard.scancapture.ScanCaptureActivity;
import com.huaxin.common.BaseFragment;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.InfoMainTypeListDTO;
import com.huaxin.common.Entity.InfoType;
import com.huaxin.common.Global;
import com.huaxin.common.findutils.FTTabLayout;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.hxcloud.R;
import com.huaxin.hxcloud.activity.CommonWebActivity;
import com.huaxin.hxcloud.find.BannerAdapter;
import com.huaxin.hxcloud.find.FindSearchActivity;
import com.huaxin.hxcloud.find.ReportSayActivity;
import com.huaxin.hxcloud.find.ViewpagerAdapter;
import com.huaxindata.common.util.HxLogUtils;
import com.huaxindata.im.main.contactview.friend.HxPersonalCenterActivity;
import com.huaxindata.im.model.contact.ContactPerson;
import com.jude.rollviewpager.OnItemClickListener;
import com.jude.rollviewpager.RollPagerView;

import org.json.JSONObject;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 首页Fragment
 * Created by hebing on 2017/5/15.
 */

public class InfoPagerFragment extends BaseFragment {


    @BindView(R.id.find_toolbar_scan)
    ImageView     mFindToolbarScan;
    @BindView(R.id.find_search_tv)
    TextView      mFindSearchTv;
    @BindView(R.id.pager_info_list2_skip)
    ImageView     mPagerInfoList2Skip;
    @BindView(R.id.coor_banner_view)
    RollPagerView mCoorBannerView;
    @BindView(R.id.find_top_rv)
    RecyclerView  mFindTopRv;
    @BindView(R.id.find_top_rv_more)
    RecyclerView  mFindTopRvMore;
    @BindView(R.id.lay_header)
    LinearLayout  mLayHeader;
    @BindView(R.id.btn_back)
    ImageView     mBtnBack;
    @BindView(R.id.tab_layout_vp)
    FTTabLayout   mTabLayoutVp;
    @BindView(R.id.btn_send)
    ImageView     mBtnSend;
    @BindView(R.id.appbar)
    AppBarLayout  mAppBarLayout;
    @BindView(R.id.vp_list)
    ViewPager     mVpList;
    private TopAdapter1 topAdapter1;
    private TopAdapter2 topAdapter2;
    //是否隐藏了头部
    private boolean isHideHeaderLayout = false;
    private ViewpagerAdapter mainTabFragmentAdapter;//fragment的适配器

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_info_pager_fragment;
    }

    @Override
    protected void initView(final View inflat) {
        super.initView(inflat);
        initBanndler();
        initGridLayout();
        initTabView();//将viewpager 与 tab 关联，并刷新适配器
        initAppBarLayout();
    }


    //轮播图
    private void initBanndler() {
        mCoorBannerView.setAnimationDurtion(1000);
        mCoorBannerView.setAdapter(new BannerAdapter());
        mCoorBannerView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Intent intent = new Intent(getContext(), HxBannerInfoActivity.class);
                getContext().startActivity(intent);
            }
        });
    }

    private void initGridLayout() {
        GridLayoutManager layoutManager2 = new GridLayoutManager(getContext(), 5);
        topAdapter2 = new TopAdapter2(getContext());
        mFindTopRvMore.setLayoutManager(layoutManager2);
        mFindTopRvMore.setAdapter(topAdapter2);

        GridLayoutManager layoutManager1 = new GridLayoutManager(getContext(), 5);
        topAdapter1 = new TopAdapter1(getContext(), mFindTopRvMore);
        mFindTopRv.setLayoutManager(layoutManager1);
        mFindTopRv.setAdapter(topAdapter1);
    }

    private void initTabView() {
        if (Global.user != null) {
            if (TextUtils.isEmpty(Global.user.getOrgCode())) {
                mainTabFragmentAdapter = new ViewpagerAdapter(getChildFragmentManager(), getContext(), 1);//游客
            } else {
                mainTabFragmentAdapter = new ViewpagerAdapter(getChildFragmentManager(), getContext(), 2);//企业
            }
            mVpList.setAdapter(mainTabFragmentAdapter);
            mVpList.setOffscreenPageLimit(mainTabFragmentAdapter.getCount());
            mTabLayoutVp.setViewPager(mVpList);
            mainTabFragmentAdapter.notifyDataSetChanged();
        }
    }


    private void initAppBarLayout() {
        LayoutTransition mTransition = new LayoutTransition();
        /**
         * 添加View时过渡动画效果
         */
        ObjectAnimator addAnimator = ObjectAnimator.ofFloat(null, "translationY", 0, 1.f).
                setDuration(mTransition.getDuration(LayoutTransition.APPEARING));
        mTransition.setAnimator(LayoutTransition.APPEARING, addAnimator);
        //header layout height
        mAppBarLayout.measure(0, 0);
        final int headerHeight = mAppBarLayout.getMeasuredHeight();
        Log.d(TAG, "initAppBarLayout: ---->" + headerHeight);
        mAppBarLayout.setLayoutTransition(mTransition);
        mAppBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                verticalOffset = Math.abs(verticalOffset);
                Log.d(TAG, "onOffsetChanged: ----->" + (verticalOffset >= headerHeight));
                if (verticalOffset >= headerHeight) {
                    isHideHeaderLayout = true;
                    isConcealView(isHideHeaderLayout);
                    for (int i = 0; i < mainTabFragmentAdapter.getFragments().size(); i++) {
                        ListFragment fragment = (ListFragment) mainTabFragmentAdapter.getFragments().get(i);
                        fragment.tooglePager(true);
                    }

                    //当偏移量超过顶部layout的高度时，我们认为他已经完全移动出屏幕了
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) mLayHeader.getLayoutParams();
                            mParams.setScrollFlags(0);
                            mLayHeader.setLayoutParams(mParams);
                            mLayHeader.setVisibility(View.GONE);
                        }
                    }, 300);
                }
            }
        });
    }


    private InfoMainTypeListDTO _infoMainTypeList;

    @Override
    public void requestData() {
        String temp = getACache().getAsString(Constants.AC_MAIN_INFO_TYPE);
        if (temp != null) {
            _infoMainTypeList = getGson().fromJson(
                    temp, InfoMainTypeListDTO.class);
            updateView();
        } else {
            ApiRequestData(LOADING, null);
        }

    }

    public void updateView() {
        String temp = getACache().getAsString(Constants.AC_MAIN_INFO_TYPE);
        if (temp != null) {
            _infoMainTypeList = getGson().fromJson(
                    temp, InfoMainTypeListDTO.class);
        }
        if (_infoMainTypeList == null)
            return;
        List<InfoType> infoTypeList = _infoMainTypeList.getInfoTypes();
        updateAdpater(infoTypeList);
    }

    private void updateAdpater(List<InfoType> infoTypeList) {
        int size = infoTypeList.size();
        for (InfoType infoType : infoTypeList) {
            topAdapter1.getDatas().add(infoType);
        }
        if (size > 9) {
            for (int i = 9; i < size; i++) {
                topAdapter2.getDatas().add(infoTypeList.get(i));
            }
        }
        topAdapter1.notifyDataSetChanged();
        topAdapter2.notifyDataSetChanged();
    }


    private void ApiRequestData(int status, final PullToRefreshBase<RecyclerView> refreshView) {
        Call<InfoMainTypeListDTO> call = getRequestApi().getMainInfoType();
        autoClose(call);
        call.enqueue(new Callback<InfoMainTypeListDTO>() {
            @Override
            public void onResponse(Call<InfoMainTypeListDTO> call, Response<InfoMainTypeListDTO>
                    response) {
                if (response.isSuccessful()) {
                    InfoMainTypeListDTO infoMainTypeListDto = response.body();
                    if (infoMainTypeListDto != null && infoMainTypeListDto.isSuccessful()) {
                        if (refreshView != null) {
                            refreshView.onRefreshComplete();
                        } else {
                            updateLoadStatus(LOAD_SUCCESS);
                        }
                        getACache().put(Constants.AC_MAIN_INFO_TYPE, getGson().toJson(infoMainTypeListDto));
                        updateAdpater(infoMainTypeListDto.getInfoTypes());
                        return;
                    }
                }
                if (refreshView != null) {
                    refreshView.onRefreshComplete();
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
                ToastUtil.showToast("数据异常");

            }

            @Override
            public void onFailure(Call<InfoMainTypeListDTO> call, Throwable t) {
                ToastUtil.showToast("网络故障");
                if (refreshView != null) {
                    refreshView.onRefreshComplete();
                } else {
                    updateLoadStatus(LOAD_FAILURE);
                }

            }
        });
    }


    @OnClick({R.id.find_search_tv, R.id.pager_info_list2_skip, R.id.find_toolbar_scan
            , R.id.btn_send, R.id.btn_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.find_search_tv: //搜索
                Intent intent = new Intent(getContext(), FindSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.btn_send:
            case R.id.pager_info_list2_skip://发表说说
                startActivityForResult(new Intent(getContext(), ReportSayActivity.class), 0);
                break;
            case R.id.find_toolbar_scan://扫一扫
                startActivityForResult(new Intent(getActivity(), ScanCaptureActivity.class), 0);
                break;
            case R.id.btn_back:
                //监听返回键
                if (isHideHeaderLayout) {
                    isHideHeaderLayout = false;
                    isConcealView(isHideHeaderLayout);
                    for (int i = 0; i < mainTabFragmentAdapter.getFragments().size(); i++) {
                        ListFragment fragment = (ListFragment) mainTabFragmentAdapter.getFragments().get(i);
                        //回到顶部
                        fragment.getRvList().scrollToPosition(0);
                        fragment.tooglePager(false);
                    }
                    mLayHeader.setVisibility(View.VISIBLE);
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) mLayHeader.getLayoutParams();
                            mParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL |
                                    AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
                            mLayHeader.setLayoutParams(mParams);
                        }
                    }, 300);
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == Activity.RESULT_OK) {
                String dataString = data.getStringExtra("code");
                if (dataString != null) {
                    if (dataString.contains("#&")) {//拼接字符串二维码解析
                        String[] split = dataString.split("#&");
                        if (split.length == 6) {
                            //id  name 图片链接 手机号码
                            ContactPerson person = new ContactPerson(split[2], split[4],split[3], split[5], null, null);
                      /*  ContactInfoDialog dialog = new ContactInfoDialog(getContext());
                        dialog.show(person);*/
                            Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putParcelable("contact", person);
                            intent.putExtras(bundle);
                            getActivity().startActivity(intent);
                        }
                    } else {
                        try {
                            String dataStr = data.getStringExtra("code");
                            JSONObject jsonObject = new JSONObject(dataStr);
                            String typeValue = (String) jsonObject.get("typeValue");
                            if (typeValue.equals("fre")) {
                                String nameID = (String) jsonObject.get("nameID");
                                String name = (String) jsonObject.get("name");
                                String phone = (String) jsonObject.get("phone");
                                String imgeUrl = (String) jsonObject.get("imgeUrl");
                                ContactPerson person = new ContactPerson(nameID, imgeUrl, name, phone, "", "");
                                Intent intent = new Intent(getActivity(), HxPersonalCenterActivity.class);
                                Bundle bundle = new Bundle();
                                bundle.putParcelable("contact", person);
                                intent.putExtras(bundle);
                                getActivity().startActivity(intent);
                            }
                        } catch (Exception e) {

                        }
                    }

                }
            }
        }
    }


    /*  @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    String dataStr = data.getStringExtra("code");
                    JSONObject jsonObject = new JSONObject(dataStr);
                    String typeValue = (String) jsonObject.get("typeValue");
                    if (typeValue.equals("fre")) {
                        String nameID = (String) jsonObject.get("nameID");
                        String name = (String) jsonObject.get("name");
                        String phone = (String) jsonObject.get("phone");
                        String imgeUrl = (String) jsonObject.get("imgeUrl");
                        ContactPerson person = new ContactPerson(nameID, name, imgeUrl, phone, null);
                        GroupFragmentInfo.showContactInfo(getActivity(), person);
                    }
                } catch (Exception e) {

                }
            }
        }
    }*/

    //监听返回键
    public boolean onKeyDown() {
        //监听返回键
        if (isHideHeaderLayout) {
            isHideHeaderLayout = false;
            isConcealView(isHideHeaderLayout);
            for (int i = 0; i < mainTabFragmentAdapter.getFragments().size(); i++) {
                ListFragment fragment = (ListFragment) mainTabFragmentAdapter.getFragments().get(i);
                //回到顶部
                fragment.getRvList().scrollToPosition(0);
                fragment.tooglePager(false);
            }
            mLayHeader.setVisibility(View.VISIBLE);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    AppBarLayout.LayoutParams mParams = (AppBarLayout.LayoutParams) mLayHeader.getLayoutParams();
                    mParams.setScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL |
                            AppBarLayout.LayoutParams.SCROLL_FLAG_EXIT_UNTIL_COLLAPSED);
                    mLayHeader.setLayoutParams(mParams);
                }
            }, 300);
            return true;
        } else {
            return false;
        }
    }

    /**
     * @desc 是否隐藏控件
     * @author songxf
     * created at 2017/8/11 13:07
     */
    private void isConcealView(boolean isConceal) {
        if (!isConceal) {
            mBtnBack.setVisibility(View.GONE);
            mBtnSend.setVisibility(View.GONE);
        } else {
            mBtnBack.setVisibility(View.VISIBLE);
            mBtnSend.setVisibility(View.VISIBLE);
        }
    }

}
